<template>

  <el-row>
    <el-input
        v-model="filterfield.username"
        class="w-50 m-2"
        size="default"
        placeholder="Please Input"
        style = 'width:170px'
    >
      <template #prefix>
        <el-icon>
          <search/>
        </el-icon>
      </template>
    </el-input>

    <el-button @click="initData" type="primary"  >
      <el-icon>
        <search/>
      </el-icon>
    </el-button>

    <el-button @click="clearFileterTheninitData" type="primary">
      <el-icon><RefreshRight/></el-icon>
    </el-button>

    <el-button v-role="userRole" :roles="['admin']" type="success" @click="addUserVisable=true">
      <el-icon>
        <plus/>
      </el-icon>
    </el-button>

  </el-row>

  <el-table :data="tableData" stripe height="250" table-layout="fixed">
    <el-table-column prop="userId" label="userId"/>
    <el-table-column prop="username" label="username"/>
    <el-table-column prop="sex" label="sex"/>
    <el-table-column prop="addtime" label="addtime"/>
    <el-table-column fixed="right" label="Operations">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="showDetail(scope.row)">
          Detail
        </el-button>

        <el-button  v-role="userRole" :roles="['admin']"  link type="primary" size="small" @click="editUserFun(scope.row)">
          Edit
        </el-button>

        <el-popconfirm
            confirm-button-text="Yes"
            cancel-button-text="No"
            title="Are you sure to delete this?"
            @confirm="confirmEvent(scope.row)"
        >
          <template #reference>
            <el-button v-role="userRole" :roles="['admin']" link type="primary" size="small">Delete</el-button>
          </template>
        </el-popconfirm>


      </template>
    </el-table-column>
  </el-table>

  <div class="demo-pagination-block">
    <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4" :page-sizes="[5, 20, 100]"
                   :small="small" :disabled="disabled" :background="background"
                   layout="total, sizes, prev, pager, next, jumper"
                   v-model:total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
  </div>

  <el-dialog title="Detail" v-model="detailVisible" width="300px">

    <el-form>
      <el-form-item label="userId">
        <el-input v-model="detail.userId" disabled></el-input>
      </el-form-item>
      <el-form-item label="Username" prop="username">
        <el-input v-model="detail.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="Sex" prop="sex">
        <el-select v-model="detail.sex" placeholder="Select sex" disabled>
          <el-option v-for="item in sexOptions" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="addtime">
        <el-input v-model="detail.addtime" disabled></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="detailVisible = false">Cancel</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog title="Edit" v-model="editVisible" width="300px">
    <el-form :model="editUser" :rules="rules" ref="editForm">
      <el-form-item label="userId">
        <el-input v-model="editUser.userId" disabled></el-input>
      </el-form-item>
      <el-form-item label="Username" prop="username">
        <el-input v-model="editUser.username"></el-input>
      </el-form-item>
      <el-form-item label="Sex" prop="sex">
        <el-select v-model="editUser.sex" placeholder="Select sex">
          <el-option v-for="item in sexOptions" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="addtime">
        <el-input v-model="editUser.addtime" disabled></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editVisible = false">Cancel</el-button>
        <el-button type="primary" @click="editUserOkFun()">
          Confirm
        </el-button>
      </span>
    </template>

  </el-dialog>


  <el-dialog title="Add" v-model="addUserVisable" width="300px">
    <el-form :model="addUser" :rules="rules" ref="editForm">

      <el-form-item label="Username" prop="username">
        <el-input v-model="addUser.username"></el-input>
      </el-form-item>
      <el-form-item label="Sex" prop="sex">
        <el-select v-model="addUser.sex" placeholder="Select sex">
          <el-option v-for="item in sexOptions" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>

    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addUserVisable = false">Cancel</el-button>
        <el-button type="primary" @click="addUserOkFun">
          Confirm
        </el-button>
      </span>
    </template>

  </el-dialog>


</template>

<script>
import {ElLoading, ElMessageBox, ElMessage} from "element-plus";
import {selectPage, selectPageSyn, sexTypeApi, updateUserApi, addUserApi, deleteUserApi} from "@/api/server";
import {Document, Setting, UserFilled, Plus, Check, Search,RefreshRight} from "@element-plus/icons-vue";


export default {
  name: "UserManager",
  data() {
    return {
      userRole: 'admin', 

      tableData: [],
      currentPage4: 1,
      pageSize4: 5,
      total: 0,
      small: false,
      background: false,
      disabled: false,

      detail: {},
      detailVisible: false,

      editUser: {
        username: "",
        sex: "",
        userId: 0,
      },
      editVisible: false,
      rules: {
        userId: [
          {required: true, message: "Please enter User ID", trigger: "blur"},
        ],
        username: [
          {required: true, message: "Please enter Username", trigger: "blur"},
        ],
        sex: [
          {required: true, message: "Please select sex", trigger: "change"},
        ],
      },

      addUserVisable: false,
      addUser: {
        // username: "", sex: ""
      },

      sexOptions: null,

      filterfield: {
        username: ""
      },

    };
  },
  methods: {
    showMessageBoxError() {
      ElMessageBox.confirm("Incorrect password. Please try again.", "Error", {
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        showCancelButton: false,
        type: "error",
        center: true,
      })
          .then(() => {
            // User clicked "OK" (confirm button).
            // You can perform additional actions here if needed.
          })
          .catch(() => {
            // User clicked "Cancel" or closed the dialog.
            // You can perform additional actions here if needed.
            console.log("catch");
          });
    },


    showMessageError(type, message) {
      ElMessage({
        message: message,
        //warning 、error、success
        type: type,
      });
    },

    confirmEvent(row) {
      console.log(row);
      //loading
      const loadingInstance = ElLoading.service({fullscreen: true});
      console.log(Date.now() + 'delete loading');
      deleteUserApi(row.userId)
          .then((res) => res.data)
          .then((res) => {
            console.log(Date.now() + 'delete loading close');
            loadingInstance.close();
            if (res.resultCode === 0) {
              this.showMessageError("success", "delete success");
              //刷新表格
              this.initData();
            } else {
              this.showMessageError("error", res.resultMessage);
            }
          })
          .catch((res) => {
            console.log(res);
            this.showMessageError("error", res);
          })
          .finally(() => {
            console.log(Date.now() + 'delete loading close');
            loadingInstance.close();
          });
    },

    // 编辑
    editUserFun(row) {
      //停止对象绑定，防止修改 表单 ，表格中的记录跟着修改
      this.editUser = JSON.parse(JSON.stringify(row));
      // this.editUser = row;
      this.editVisible = true;
    },

    // 编辑-取消
    editUserCanelFun(row) {
      this.editUser = {};
      this.editVisible = false;
    },

    // 编辑-确定
    editUserOkFun() {

      // Validate the form and save the changes
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          // Handle the save logic here (e.g., update user data)
          // After saving, close the dialog
          console.log("合法" + valid + JSON.stringify(this.editUser));

          //loading
          const loadingInstance = ElLoading.service({fullscreen: true});

          updateUserApi(this.editUser)
              .then((res) => res.data)
              .then((res) => {
                if (res.resultCode === 0) {
                  this.showMessageError("success", "edit success");
                  this.editVisible = false;

                  //刷新表格
                  this.initData();

                } else {
                  this.showMessageError("error", res.resultMessage);
                }
              })
              .catch((res) => {
                console.log(res);
                this.showMessageError("error", res);
              })
              .finally(() => {
                console.log("close");
                loadingInstance.close();

              });
        } else {
          // If validation fails, do nothing (the form will display error messages)
          console.log("不合法" + valid + JSON.stringify(this.editUser));
        }
      });
    },

    addUserOkFun() {

      // Validate the form and save the changes
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          // Handle the save logic here (e.g., update user data)
          // After saving, close the dialog
          this.addUserVisable = false;
          console.log("合法" + valid + JSON.stringify(this.addUser));

          //loading
          const loadingInstance = ElLoading.service({fullscreen: true});

          addUserApi(this.addUser)
              .then((res) => res.data)
              .then((res) => {
                if (res.resultCode === 0) {
                  this.showMessageError("success", "add success");
                  //刷新表格
                  this.initData();
                  this.addUserVisable = false;
                  //清空
                  this.addUser = {};
                } else {
                  this.showMessageError("error", res.resultMessage);
                }
              })
              .catch((res) => {
                console.log(res);
                this.showMessageError("error", res);
              })
              .finally(() => {
                console.log("close");
                loadingInstance.close();
              });
        } else {
          // If validation fails, do nothing (the form will display error messages)

          console.log("不合法" + valid + JSON.stringify(this.editUser));
        }
      });
    },

    //详情
    showDetail(row) {
      this.detail = row;
      this.detailVisible = true;
    },

    handleSizeChange(number) {
      //设置分页大小
      console.log(number);
      this.initData();
    },
    handleCurrentChange(number) {
      //跳转到页
      console.log(number);
      this.initData();
    },

    clearFileterTheninitData(){
      this.filterfield.username = '';
      this.initData();
    },

    async initData() {
      //loading
      const loadingInstance = ElLoading.service({fullscreen: true});
      console.log(Date.now() + 'initdata loading');
      var response = await selectPageSyn(this.pageSize4, this.currentPage4, this.filterfield.username);
      if (response && response.data.resultCode === 0) {
        this.tableData = response.data.data.list;
        this.total = parseInt(response.data.data.total);
      } else if (response && response.data) {
        this.showMessageError('error', response.data.resultMessage);
      }

      // var response = selectPage(this.pageSize4, this.currentPage4, this.filterfield.username);
      // response
      //     .then((res) => res.data) //数据过滤，只要后端返回的data数据
      //     .then((res) => {
      //
      //       this.tableData = res.data.list;
      //       this.total = parseInt(res.data.total);
      //     })
      //     .catch((err) => {
      //       this.showMessageError("error", err);
      //     })
      //     .finally(() => {
      //       console.log(Date.now() + 'initdata loading close');
      //       loadingInstance.close();
      //     });
      loadingInstance.close();
      console.log(Date.now() + 'initdata loading close');
      console.log(Date.now() + "initData end!!! 验证axios 是个阻塞方法");
    },

    sexType() {
      var response = sexTypeApi();
      response
          .then((res) => {
                if (res && res.data && res.data.resultCode === 0) {
                  this.sexOptions = res.data.data;
                } else if (res && res.data) {
                  this.showMessageError("error", res.data.resultMessage)
                }
              }
          )
          .catch((err) => {
            console.log(err)
          });
    },
  },
  mounted() {
    this.initData();
    this.sexType();
  },
  components: {
    Plus, Search,RefreshRight
  }

};
</script>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
